package com.cloudcc.mobile.view.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase.OnRefreshListener;
import com.cloudcc.mobile.weight.ui.PullToRefreshWebView;

/**
 * 侧拉网页加载页面
 * 
 * @author Administrator
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class WebviewFive extends BaseWebActivity {
	private String mEns = RunTimeManager.getInstance().getlanguage();
	private String urlString;
	private String filePath;
	private Uri uri;
	private boolean isFrist = true;
	private ImageView menubtn;
	private RelativeLayout webview;
	/** 显示格式化日期模板 */
	private final static String DATE_FORMAT_STR = "yyyy年MM月dd日 HH:mm";

	@Override
	protected void initUI() {
		super.initUI();
		mRefresh = (PullToRefreshWebView) findViewById(R.id.weixin);
		mWebView = mRefresh.getRefreshableView();
		back = (ImageView) findViewById(R.id.fanhui);
		refresh = (ImageView) findViewById(R.id.shuaxin);
		menubtn = (ImageView) findViewById(R.id.webview_menubtn);
		ctrl_container = (RelativeLayout) findViewById(R.id.caozuo);
		ctrl_container.setVisibility(View.GONE);
		webview = (RelativeLayout) findViewById(R.id.webview_yemian);
		ctrl_container.setVisibility(View.GONE);
		mWebView.setVisibility(View.GONE);
		setLastUpdateTime();
		addListener();

	}

	@Override
	protected void initSetting() {
		super.initSetting();

		// if (isFrist) { // session失效测试
		// CookieSyncManager.createInstance(this);
		// CookieManager cookieManager = CookieManager.getInstance();
		// cookieManager.setAcceptCookie(true);
		// cookieManager.removeSessionCookie();// 移除
		// cookieManager.removeAllCookie();
		// CookieSyncManager.getInstance().sync();
		// }

		mWebView.requestFocus();
		mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);// 防止滑动的时候闪屏
		mUrl = AppContext.urlString;
		mWebView.loadUrl(mUrl);
		mWebView.reload();

		WebSettings webstting = mWebView.getSettings();
		webstting.setJavaScriptEnabled(true);
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);
		webstting.setCacheMode(WebSettings.LOAD_DEFAULT);// 是否缓存
		webstting.setBlockNetworkImage(false);
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);

	}

	@Override
	protected void initClient() {

		super.initClient();
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				showProgress();
				LogUtils.d("webview", "开始加载url" + url);
				urlString = url;
				if (url.equals(AppContext.indexUrl)) {
					WebviewFive.this.finish();
					mWebView.stopLoading();
					return;
				}
				if (url.equals(UrlTools.loginurl)) {
					Intent intent = new Intent(UrlTools.loginurl);
					mContext.sendBroadcast(intent);
				}
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				LogUtils.d("webview", "加载完成url" + url);
				stopProgress();
				setLastUpdateTime();// 刷新时间
				AppContext.isFirst = true;
				mWebView.setVisibility(View.VISIBLE);
				ctrl_container.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				LogUtils.d("webview", "跳转：" + url);
				if (UrlManager.isWapLogin(url)) {// 跳转去登录
					EventEngine.register(WebviewFive.this);
					Intent intent = new Intent(mContext, BindActivity.class);
					startActivity(intent);
					return true;
				}
				// if (url.contains("/wx_taskquery.action?m=query&id=")) {
				// String id = url.substring(
				// Tools.getCharacterPosition(url, "=", 2) + 1,
				// Tools.getCharacterPosition(url, "&", 2));
				// Intent intent = new Intent(mContext, RelevantActivtiy.class);
				// intent.putExtra("web", id);
				// intent.putExtra("web.url", UrlManager.getRootUrl()
				// + UrlTools.getObjectUrl(id));
				// startActivity(intent);
				// return true;
				// } else if (url.contains("/weiquery.action?m=query&id=")) {
				// String id = url.substring(
				// Tools.getCharacterPosition(url, "=", 2) + 1,
				// url.length());
				// Tools.i("followService", id);
				// Intent intent = new Intent(mContext, RelevantActivtiy.class);
				// intent.putExtra("web", id);
				// intent.putExtra("web.url",
				// UrlManager.APP_UR + UrlTools.getObjectUrl(id));
				// startActivity(intent);
				// return true;
				// } else if (url.contains("/weiquery.action?id=")) {
				// String type = url.substring(
				// Tools.getCharacterPosition(url, "=", 2) + 1,
				// url.length());
				// Tools.i("followService", type);
				// if (type.equals("query")) {
				// String id = url.substring(
				// Tools.getCharacterPosition(url, "=", 1) + 1,
				// url.length() - 8);
				// Tools.i("followService", id);
				// Intent intent = new Intent(mContext,
				// RelevantActivtiy.class);
				// intent.putExtra("web", id);
				// intent.putExtra("web.url",
				// UrlManager.APP_UR + UrlTools.getObjectUrl(id));
				// startActivity(intent);
				// return true;
				// } else {
				//
				// }
				//
				// }

				if (UrlManager.isHome(url)) {
					WebviewFive.this.finish();
					return true;
				} else {
					// 自身加载新链接,不做外部跳转
					view.loadUrl(url);
					return true;
				}
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				AppContext.isError = true;
				
//				if ("en".equals(mEns)) {
//					view.loadUrl("file:///android_asset/html/en_error.html");
//				}else{
					view.loadUrl("file:///android_asset/html/error.html");
//			}
			}
		});
	}

	protected void setLastUpdateTime() {
		mRefresh.setLastUpdatedLabel(new SimpleDateFormat(DATE_FORMAT_STR,
				Locale.CHINA).format(new Date()));
	}

	/**
	 * 监听 mWebView.goBack(); //后退 mWebView.goForward();//前进 mWebView.reload();
	 * //刷新
	 */
	private void addListener() {
		mRefresh.setOnRefreshListener(new OnRefreshListener<WebView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<WebView> refreshView) {
				mWebView.reload();
				mRefresh.onPullDownRefreshComplete();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<WebView> refreshView) {
			}
		});
		menubtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// MyApplication.menu.toggle();//TODO menu处理
			}
		});
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (urlString.equals(UrlTools.weixinUrl + UrlTools.menuurl)) {
					mWebView.reload(); // 刷新
				} else {
					mWebView.goBack(); // 后退
				}
			}
		});
		refresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mWebView.reload(); // 刷新
			}
		});

	}
}
